package com.wz.fragment;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.speech.SpeechRecognizer;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;

import com.wz.activity.MainActivity;
import com.wz.activity.R;
import com.wz.activity.RecognitionParam;
import com.wz.activity.SendMesgActivity;
import com.wz.adapter.ContactExpAdapter;
import com.wz.bean.ContactBean;
import com.wz.util.ChineseToEnglish;
import com.wz.util.ToastUtil;


public class ContactListFragment extends Fragment {

	// 存放联系人信息
	private TreeMap<String, List<ContactBean>> contactData = new TreeMap<String, List<ContactBean>>();

	// 按姓氏分组,surnameGroup 长度和childContactInfo是完全一样的
	private List<String> surnameGroup = new ArrayList<String>();
	// 对应姓氏下联系人姓名
	private List<List<ContactBean>> childContactInfo = new ArrayList<List<ContactBean>>();

	private ExpandableListView expListView;
	private ContactExpAdapter contactExpAdapter;
	private EditText etSearch;
	private FloatingActionButton floatBtn;

	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

		View view = inflater.inflate(R.layout.frag_contactlist, container, false);
		
		etSearch = (EditText) view.findViewById(R.id.etSearch);

		expListView = (ExpandableListView) view.findViewById(R.id.expList);
		
		floatBtn = (FloatingActionButton) view.findViewById(R.id.wz_recognition_btn);
		
		contactExpAdapter = new ContactExpAdapter(this.getContext(),surnameGroup,childContactInfo);
		expListView.setAdapter(contactExpAdapter);
		
		initEvent();
		
        resolveContact();
		
		groupingWithData(null);
		
		contactExpAdapter.notifyDataSetChanged();
		
		//展开全部分组
		int size = surnameGroup.size();
		for (int i = 0; i < size; i++) {
			expListView.expandGroup(i);
		}
		
		return view;
	}
	
	private void initEvent(){
		
		expListView.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

				ContactBean contactBean = childContactInfo.get(groupPosition).get(childPosition);
				String phoneNum = contactBean.getPhoneNum();
				
				callTel(phoneNum);
				
				return true;
			}
		});
		
		floatBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				recognizeSpeech();
			}
		});
		
		etSearch.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				String searchText=etSearch.getText().toString();
				
				groupingWithData(searchText);
				
				contactExpAdapter.notifyDataSetChanged();
				
				//展开全部分组
				int size = surnameGroup.size();
				for (int i = 0; i < size; i++) {
					expListView.expandGroup(i);
				}
			}
		});
		
	}
	
	/**
	 * 调用识别
	 */
	private void recognizeSpeech(){
		Intent intent = new RecognitionParam().bindParams(getActivity());
		intent.setAction("com.baidu.action.RECOGNIZE_SPEECH");
        startActivityForResult(intent, 1);
	}
	/**
	 * 直接拨打电话
	 */
	private void callTel(String phoneNum){
		Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phoneNum));
		startActivity(intent);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		  if (resultCode == android.app.Activity.RESULT_OK) {
	            onResults(data.getExtras());
	        }
	}
	
	 public void onResults(Bundle results) {
	       
	        ArrayList<String> nbest = results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
	      
	        int size = nbest.size();
	        for (int i = 0; i < size; i++) {
	        	String result = nbest.get(i);

				if(result.contains("拨打电话")  &&  result.length() <= 6){
					 MainActivity.instance().speak("请问你要打给谁");
					 break;
				}else if(result.startsWith("打给") && result.length() >= 4){
					String name = result.substring(2);
					String phoneNum = getPhoneNumByName(name);
					if(phoneNum == null){
						String text = "没有找到"+name+"的联系方式";
					    MainActivity.instance().speak(text);
					    ToastUtil.showLong(getContext(), text);
					    return;
					}
					callTel(phoneNum);
				}else if(result.startsWith("打电话给") && result.length() >= 6){
					String name = result.substring(4);
					String phoneNum = getPhoneNumByName(name);
					if(phoneNum == null){
						String text = "没有找到"+name+"的联系方式";
					    MainActivity.instance().speak(text);
					    ToastUtil.showLong(getContext(), text);
					    return;
					}
					callTel(phoneNum);
				}else if(result.contains("发送短信")){
					Intent intent = new Intent(getActivity(), SendMesgActivity.class);
					intent.putExtra(SendMesgActivity.KEY_FESTIVAL_ID, 9);
					startActivity(intent);
				}else if(i == size-1){
					MainActivity.instance().speak("请说人话!");
				}
			}
	        
	        
	        ToastUtil.showLong(getContext(), nbest.toString());
	        
	       
	  }
	 
	 /**
	  * 根据联系人姓名获取电话号码,(注意这里没有对重名处理)
	  * @param name
	  */
	 private String getPhoneNumByName(String name){
		/* Set<Entry<String, List<ContactBean>>> entrySet = contactData.entrySet();
		 Iterator<Entry<String, List<ContactBean>>> iterator = entrySet.iterator();
		 */
		 //获取姓名简拼,用于获取这个姓名所在的组,这样遍历比较快
		 String jianpin = ChineseToEnglish.getFirstChar(name);
		 String group = jianpin.substring(0, 1);
		 //获取该组的全部人员
		
		 if(contactData.containsKey(group)){
			 List<ContactBean> list = contactData.get(group);
			 for (ContactBean contactBean : list) {
				 if(contactBean.getName().equals(name)){
					 return contactBean.getPhoneNum();
				 }
			}
		 }
		 return null;
	 }
	 
	 
    /**
     * 联系人分组
     */
	private void groupingWithData(String searchText){
		surnameGroup.clear();
		childContactInfo.clear();
		
		/**
		 * 如果搜索文本不为空,并且长度是 1 ,则使用分组查询,searchText 为组名
		 */
		if(!TextUtils.isEmpty(searchText) 
				&& (searchText.length()==1)
				&& !ChineseToEnglish.isChineseChar(searchText)
				&& !ChineseToEnglish.isNumeric(searchText)
				){
			if(contactData.containsKey(searchText)){
				surnameGroup.add(searchText);
				childContactInfo.add(contactData.get(searchText));
			}
			
			return;
		}
		
		//否则根据姓名,简写,全拼搜索
		Set<Entry<String, List<ContactBean>>> entrySet = contactData.entrySet();
		Iterator<Entry<String, List<ContactBean>>> iterator = entrySet.iterator();
		
		if(!TextUtils.isEmpty(searchText)){
			while (iterator.hasNext()) {
				Entry<String, List<ContactBean>> next = iterator.next();
				String key = next.getKey();
				List<ContactBean> value = next.getValue();
				
				List<ContactBean> useful = null;
				//将输入的字符串转为小写,因为中文转换后的就是小写
				String lowerCase = searchText.toLowerCase(Locale.ENGLISH); 
				for (ContactBean contactBean : value) {
					if((contactBean.getName().contains(lowerCase))||
							(contactBean.getFirstChar().contains(lowerCase))||
							(contactBean.getFullpinyin().contains(lowerCase)) ||
							(contactBean.getPhoneNum().contains(lowerCase)) ){
						if(useful==null){
							useful = new ArrayList<ContactBean>();
						}
						//有效数据
						useful.add(contactBean);
					}
				}
				// 如果数据不为null,说明改组有匹配到的结果
				if(useful != null){
					surnameGroup.add(key);
					childContactInfo.add(useful);
				}
			}
			return ;
		}
	
		while (iterator.hasNext()) {
			Entry<String, List<ContactBean>> next = iterator.next();
			String key = next.getKey();
			surnameGroup.add(key);
			childContactInfo.add(next.getValue());
		}
	}
	
	/**
	 * 获取联系人信息
	 */
	private void resolveContact(){
		
		 contactData.clear();
		
		 //存放联系人姓名
		 // ArrayList<String> names = new ArrayList<String>();
		 //ArrayList<ArrayList<String>> details = new ArrayList<ArrayList<String>>();
		
		 ContentResolver contentResolver = this.getContext().getContentResolver();
		
		 //查找全部联系人数据
		 Cursor cursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
		
		 while (cursor.moveToNext()) {
			
			 //The unique ID for a row.
			 String contact_id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
			
			 //联系人姓名
			 String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			 
			 //查询语句,用于获取电话号码
			 String selection  = ContactsContract.CommonDataKinds.Phone.CONTACT_ID+" = "+contact_id;
			 Cursor phonesCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, selection, null, null);
			 //一个人可能有多个手机号码,但是这里只要一个
			 String phoneNum = null;
			 //只在联系人有电话号码的情况下,创建联系人信息
			 if(phonesCursor.moveToNext()){
			     phoneNum = phonesCursor.getString(phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
			     
			     ContactBean contactBean = new ContactBean(name,phoneNum);
			     //全拼
			     contactBean.setFullpinyin(ChineseToEnglish.getFullSpell(name));
			     //名字每个汉字的首字母
			     String jianxie = ChineseToEnglish.getFirstChar(name);
			     contactBean.setFirstChar(jianxie);
			     //获取拼音的第一个字母作为treeMap的key,用于分组,
			     String firstChar = jianxie.substring(0, 1);
			     //如果这个key不存在,怎么创建ArrayList用于存储这组联系人信息
			     if(!contactData.containsKey(firstChar)){
			    	 contactData.put(firstChar, new ArrayList<ContactBean>());
			     }
			     //为这firstChar组添加联系人信息
			     contactData.get(firstChar).add(contactBean);
			     
			 }
			 phonesCursor.close();
			
		}
		 cursor.close(); 
	}

}
